package com.library.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 处理编码格式
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");
            // 获取请求路径
            String methodName = req.getParameter("method");
            System.out.println("BaseServlet收到请求，method=" + methodName + ", URI=" + req.getRequestURI());
            Class<? extends BaseServlet> clazz = this.getClass();
            //获取执行的方法
            Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            System.out.println("BaseServlet异常：" + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
        }
    }
}
